<template>
	<view class="container">
		<video
			id="videoContainer"
			autoplay
			class="video"
			:style="{ height: videoHeight }"
			@pause="videoPause"
			@play="videoPlay"
			@ended="videoEnded"
			:src="truePlaySrc"
			:controls="true"
			@timeupdate="timeupdate"
		>
			<cover-view class="cover-view" :style="{backgroundColor: theme.primary}" v-if="waitting">
				<cover-view class="text">开播倒计时</cover-view>
				<cover-view class="cutDownStr">{{ cutDownStr }}</cover-view>
			</cover-view>
		</video>
		<j-tabs v-if="showTabs" :tabs="tabs" @change="tabsChange" :controlIndex="tabsIndex"></j-tabs>
		<view :style="{ height: `${showTabs?scrollHeight:scrollHeightPlus}` }">
			<yxyl-album-item-list 
				:itemList="timeTableList" 
				:isLive="true" 
				:currentIndex="currentIndex" 
				:isPlaying="isPlaying" 
				:appendStr="appendStr"
				spcOpt= "true"
				@change="change">
			</yxyl-album-item-list>
		</view>
	</view>
</template>

<script>
import jTabs from '@/components/tui-tabs/j-tabs.vue'
import yxylAlbumItemList from '@/components/yxyl-album-tabs/yxyl-album-itemList.vue';
import { formatCutDownWithDay } from '@/util/dateUtil.js';
import { reportPlayTime } from '@/api/album.js';
export default {
	components: { yxylAlbumItemList, jTabs },
	data() {
		return {
			theme: this.$theme,
			id: '',
			courseName: '',
			timeTableList: [],
			currentIndex: 0,
			isPlaying: false,
			waitting: false,
			setIntervalId: '',
			cutDownStr: '',
			truePlaySrc: '',
			reviewUrls: [],
			videoContext: null,
			costPoint:0,
			costTime:0,
			classId:'',
			//tabs栏配置项目
			tabs:{
				defaultIndex: 0,
				width: '100%',
				height: '80rpx',
				list:[
					{selectedIndex: 0, text: '课程回放'},
					{selectedIndex: 1, text: '预习区'},
					{selectedIndex: 2, text: '作业区'}
				]
			},
			tabsIndex: 0,
			//0: 点击图片进入， 1: 点击按钮进入
			dist: -1,
			appendStr: '1',
			//是否首次进入
			isFirst: true,
			//播放时长上报次数
			reportIndex: 1,
			//是否显示tab切换栏， 公开课不显示
			showTabs: true
		};
	},
	onLoad(e) {
		this.videoContext = uni.createVideoContext('videoContainer');
		this.id = e.Id
		this.courseName = e.courseName
		this.dist = e.dist
		if(e.tabsIndex){
			this.tabsIndex = parseInt(e.tabsIndex)
		}
		// 公开课不显示tabs切换栏
		if(e.isOpen){
			this.showTabs = false
		}
		switch(this.tabsIndex){
			case 0:
				this.appendStr = '1'
				break
			case 1:
				this.appendStr = '2'
				break
			case 2:
				this.appendStr = '3'
				break
		}
		this.getLivePlayList(this.id)
	},
	onHide() {
		clearInterval(this.setIntervalId);
		this.videoContext.pause();
		this.videoPause();
	},
	onUnload(){
		clearInterval(this.setIntervalId);
		this.videoContext.pause();
		this.videoPause();
	},
	computed: {
		videoHeight: () => {
			const res = uni.getSystemInfoSync();
			return (res.windowWidth * 9) / 16 + 'px';
		},
		scrollHeight: function() {
			var sysInfo = uni.getSystemInfoSync();
			return sysInfo.windowHeight - (sysInfo.windowWidth * 9) / 16 - (sysInfo.windowWidth * 50) / 750 - 10 + 'px';
		},
		scrollHeightPlus: function(){
			let sysInfo = uni.getSystemInfoSync();
			let headerHeight = (sysInfo.windowWidth * 9) / 16;
			let scrollHeigt = sysInfo.windowHeight - (sysInfo.windowWidth * 9) / 16 - (sysInfo.windowWidth * 50) / 750 - 10;
			return `${headerHeight + scrollHeigt}px`;
		}
	},
	watch: {
		currentIndex(value) {
			if(this.tabsIndex == -1 || this.tabsIndex == 0){
				let currentId = this.timeTableList[value].id;
				this.getReviewList(currentId);
			}
		},
		tabsIndex(value){
			switch(value){
				case 0:
					if(!this.isFirst){
						this.appendStr = '1'
						this.refreshList()
					}
					break
				case 1:
					if(!this.isFirst){
						this.appendStr = '2'
						this.refreshList()
					}
					break
				case 2:
					if(!this.isFirst){
						this.appendStr = '3'
						this.refreshList()
					}
					break
			}
		}
	},
	methods: {
		//选择tabs栏项目
		tabsChange(selectedIndex){
			this.tabsIndex = selectedIndex			
		},
		// 列表刷新
		refreshList(){
			let refreshList = this.timeTableList
			this.timeTableList = []
			setTimeout(()=>{
				this.timeTableList = refreshList
			}, 200)
		},
		//页面跳转
		goItem(){
			switch(this.tabsIndex){
				//预习区
				case 1:
					this.goOutLine(this.timeTableList[this.currentIndex])
					break
				//作业区
				case 2:
					this.goHomeWork(this.timeTableList[this.currentIndex])
					break
			}
		},
		//跳转预习区
		goOutLine(item){
			this.$http.request({
				url: 'api/Essay/CheckByMainId',
				method: 'GET',
				showLoading: false,
				data:{
					Id: item.id,
					EssayType: 1	//1：教学大纲
				}
			}).then(resp=>{
				// 存在大纲则跳转详情页
				if(resp.essayId){
					// 有点赞评论的 preview:1预习
					uni.navigateTo({
						url: `../viewMeiPian/viewMeiPian?Id=${item.id}&essayId=${resp.essayId}&essayType=1&preview=1`
					})
				}
				// 不存在则提示
				else{
					uni.showToast({
					    title: '老师还没有布置预习作业哦',
						icon: 'none',
					    duration: 2000
					})
				}
			})
		},
		//跳转作业区
		goHomeWork(item){
			if(item.canHomework){
				let courseWeek = item.itemTitle.split(' ')[0]
				uni.navigateTo({
					url: `../meiPianList/homeworkList?mainId=${item.id}&courseName=${this.courseName}-${courseWeek}&classId=${this.id}`
				})
			}else{
				uni.showToast({
				    title: '老师还没有布置作业哦',
					icon: 'none',
				    duration: 2000
				})
			}
			
		},
		getLivePlayList(id) {
			return this.$http
				.request({
					url: 'api/LivePlayer/GetLivePlayListById',
					data: {
						Id: id
					}
				})
				.then(res => {
					let that = this;
					uni.setNavigationBarTitle({
					　　title: res.courseName
					})
					res.timeTables.forEach(function(item, index) {
						that.timeTableList.push({
							isReview: item.classStatus == 3,
							itemTitle: item.title,
							canHomework: item.canHomework,
							id: item.id,
							playListShow: item.playListShow,
							previewListShow: item.previewListShow,
							homeworkListShow: item.homeworkListShow
						})
					})
					this.isFirst = false
					// 准备中进入列表列表或者课程回放进入列表，需确认是否需要跳转直播间
					if(this.dist == 0 || this.dist == 1){
						this.getReviewList(this.timeTableList[this.currentIndex].id)
					}
				})
		},
		change(e) {
			this.currentIndex = e;
			this.goItem();
		},
		getReviewList(currentId) {
			var that = this;
			if (that.setIntervalId) clearInterval(that.setIntervalId);
			this.$http
				.request({
					url: 'api/LivePlayer/GetReviewList',
					data: {
						Id: currentId
					}
				})
				.then(res => {
					this.waitting = res.waitting;
					if (this.waitting) {
						this.clearPlayInfo();
						var date = new Date(Date.parse(res.onDateTime.replace(/-/g,'/')));
						that.setIntervalId = setInterval(function() {
							that.cutDownStr = formatCutDownWithDay(date);
							if (that.cutDownStr == '00秒' || !that.cutDownStr) {
								clearInterval(that.setIntervalId);
								this.waitting = false
								uni.redirectTo({
									url: `./video?Id=${currentId}&courseName=${this.courseName}&isOpen=${this.showTabs}`
								})
							}
						}, 1000);
					} else if (res.isLive) {
						uni.redirectTo({
							url: `./video?Id=${currentId}&courseName=${this.courseName}&isOpen=${this.showTabs}`
						})
					} else {
						this.reviewUrls = res.reviewUrls;
						this.costTime=res.costTime;
						this.classId=res.classId;
						this.handlerSrc();
					}
				})
				.catch(() => {
					that.cutDownStr = '';
					that.waitting = false;
					this.clearPlayInfo();
				});
		},
		handlerSrc(index) {
			if (!this.reviewUrls)
				uni.showToast({
					icon: 'none',
					title: '本节课暂不支持回放'
				});
			else {
				index = index || 0;
				if (index >= this.reviewUrls.length) index = 0;
				this.truePlaySrc = this.reviewUrls[index];
			}
		},
		clearPlayInfo() {
			this.reviewUrls = [];
			this.truePlaySrc = null;
			this.videoContext.stop();
			this.videoPause();
		},
		videoPause() {
			this.isPlaying = false;
		},
		videoPlay() {
			this.isPlaying = true;
		},
		videoEnded() {		
			var index = this.reviewUrls.indexOf(this.truePlaySrc);		
			if (index < this.reviewUrls.length - 1) {			
				this.truePlaySrc = this.reviewUrls[index + 1];				
			} else {
				if (this.currentIndex < this.timeTableList.length) this.currentIndex++;
				else ths.currentIndex = 0;
			}
		},
		timeupdate(e){
			if((e.detail.currentTime>parseInt(this.costPoint*this.costTime*60)))
			{								
				this.costPoint=parseInt(parseInt(e.detail.currentTime)/(this.costTime*60))+1;
				reportPlayTime(this.reportIndex, this.classId,this.timeTableList[this.currentIndex].id,this.costTime,4);
				this.reportIndex++
			}						
		}
	}
};
</script>

<style lang="scss" scoped>
.video {
	display: block;
	width: 100%;
}
.course-name {
	width: 100%;
	margin: 0 auto;
	padding: 5rpx 0;
	height: 50rpx;
	.text {
		width: 90%;
		margin: 0 auto;
	}
}
.cover-view {
	width: 100%;
	height: 100%;
	color: #f8f8f8;
	font-weight: bold;
	display: flex;
	flex-direction: column;
	justify-content: center;
	align-items: center;
	font-size: 40rpx;
	.text {
		font-size: 35rpx;
		color: #b3423e;
		padding-bottom: 10rpx;
	}
	.cutDownStr{
		width: 100%;
		height: 50rpx;
		display: flex;
		justify-content: center;
		text-align: center;
	}
}
</style>
